package com.fenxiangle.yueding.feature.focus.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.util.DateTool;
import com.fenxiangle.yueding.common.util.GetJsonDataUtil;
import com.fenxiangle.yueding.common.widget.popupwindow.PopupWindowList;
import com.fenxiangle.yueding.entity.bo.IDCardBo;
import com.fenxiangle.yueding.entity.bo.IdentificationBo;
import com.fenxiangle.yueding.entity.bo.JsonBean;
import com.fenxiangle.yueding.feature.identification.contract.IdentificationContract;
import com.fenxiangle.yueding.feature.identification.login.DaggerIdentificationComponent;
import com.fenxiangle.yueding.feature.identification.login.IdentificationPresenterModule;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Home on 2018/9/1.
 */

public class IdentificationActivity extends BaseActivity implements IdentificationContract.View {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.identification_img)
    ImageView identificationImg;
    @BindView(R.id.btn_identification)
    TextView btnIdentification;
    @BindView(R.id.layout_location)
    LinearLayout layoutLocation;
    @BindView(R.id.layout_occupation)
    RelativeLayout layoutOccupation;
    @BindView(R.id.layout_company)
    RelativeLayout layoutCompany;
    @BindView(R.id.layout_business_licence)
    RelativeLayout layoutBusinessLicence;
    @BindView(R.id.layout_identification_card)
    RelativeLayout layoutIdentificationCard;
    @BindView(R.id.layout_daren)
    RelativeLayout layoutDaren;
    @BindView(R.id.sw_daren)
    Switch swDaren;
    @BindView(R.id.layout_daren_ll)
    LinearLayout layoutDarenLl;

    @Inject
    IdentificationContract.Presenter presenter;
    @BindView(R.id.identification_content)
    TextView identificationContent;
    @BindView(R.id.id_name)
    EditText idName;
    @BindView(R.id.id_age)
    EditText idAge;
    @BindView(R.id.id_occupation)
    TextView idOccupation;
    @BindView(R.id.id_weChat)
    EditText idWeChat;
    @BindView(R.id.id_phone)
    EditText idPhone;
    @BindView(R.id.id_position)
    EditText idPosition;
    @BindView(R.id.id_companyName)
    EditText idCompanyName;
    @BindView(R.id.id_businessLicense)
    TextView idBusinessLicense;
    @BindView(R.id.id_sex)
    TextView idSex;
    @BindView(R.id.layout_sex)
    LinearLayout layoutSex;
    @BindView(R.id.id_city)
    TextView id_city;
    @BindView(R.id.id_detailAddress)
    EditText idDetailAddress;
    @BindView(R.id.layout_city)
    LinearLayout layoutCity;
    @BindView(R.id.skill)
    EditText skill;
    @BindView(R.id.layout_skillPicture)
    RelativeLayout layoutSkillPicture;

    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_identification;
    }

    @Override
    protected void initInjector() {
        DaggerIdentificationComponent.builder().identificationPresenterModule(new IdentificationPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initData() {


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    String type = "";

    @Override
    protected void initView() {
        super.initView();
        type = getIntent().getStringExtra("type");
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        AM.image().bindToCircleObject(R.drawable.iv_user_head, identificationImg);
        JSONObject jsonObject = new JSONObject();
        if (type.equals("2")) {
            initToolBar(toolbar, "身份认证", true, true);
            layoutOccupation.setVisibility(View.GONE);
            layoutCompany.setVisibility(View.GONE);
            layoutBusinessLicence.setVisibility(View.GONE);
            layoutDaren.setVisibility(View.VISIBLE);
        } else {
            initToolBar(toolbar, "老板认证", true, true);
            layoutOccupation.setVisibility(View.VISIBLE);
            layoutCompany.setVisibility(View.VISIBLE);
            layoutBusinessLicence.setVisibility(View.VISIBLE);
            layoutDaren.setVisibility(View.GONE);
        }
        swDaren.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    layoutDarenLl.setVisibility(View.VISIBLE);
                    layoutSkillPicture.setVisibility(View.VISIBLE);
                } else {
                    layoutDarenLl.setVisibility(View.GONE);
                    layoutSkillPicture.setVisibility(View.GONE);

                }
            }
        });

        try {
            presenter.select_authentication_data(type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EditOtherActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(EditOtherActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    finish();
                    break;
            }
        }
    };

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                List<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
//            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    String tx = "";

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2);
                id_city.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(R.color.div_primary)
                .setLineSpacingMultiplier(2.5f)
                .setTextColorCenter(R.color.text_primary) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        pvOptions.show();
    }

    List<File> files = null;
    String sex = "";

    @OnClick({R.id.identification_img, R.id.btn_identification, R.id.layout_identification_card, R.id.layout_sex,
            R.id.layout_city, R.id.layout_business_licence, R.id.layout_skillPicture, R.id.id_occupation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_skillPicture:
                PopupWindowList popupWindowList = new PopupWindowList(this);
                popupWindowList.showMoreWindow(layoutSkillPicture, "拍照", "相册", new PopupWindowList.PopupWindowListener() {
                    @Override
                    public void first() {
                        PictureSelector.create(IdentificationActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .compress(true)
                                .forResult(20005);
                    }

                    @Override
                    public void second() {
                        // 进入相册 以下是例子：用不到的api可以不写
                        PictureSelector.create(IdentificationActivity.this)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .theme(R.style.picture_default_style1)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                                .maxSelectNum(5)// 最大图片选择数量 int
                                .minSelectNum(1)// 最小选择数量 int
                                .imageSpanCount(4)  // 每行显示个数 int
                                .isCamera(true)// 是否显示拍照按钮 true or false
                                .compress(true)// 是否压缩 true or false
                                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .forResult(20005);//结果回调onActivityResult code     ;
                    }
                });
                break;
            case R.id.layout_sex:
                popupWindowList = new PopupWindowList(this);
                popupWindowList.showMoreWindow(identificationImg, "男", "女", new PopupWindowList.PopupWindowListener() {
                    @Override
                    public void first() {
                        sex = "0";
                        idSex.setText("男");
                    }

                    @Override
                    public void second() {
                        sex = "1";
                        idSex.setText("女");
                    }
                });
                break;
            case R.id.layout_city:
                if (isLoaded) {
                    showPickerView();
                } else {
                    T.showShort("Please waiting until the data is parsed");
                }
                break;
            case R.id.identification_img:
                popupWindowList = new PopupWindowList(this);
                popupWindowList.showMoreWindow(identificationImg, "拍照", "相册", new PopupWindowList.PopupWindowListener() {
                    @Override
                    public void first() {
                        PictureSelector.create(IdentificationActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .compress(true)
                                .forResult(10005);
                    }

                    @Override
                    public void second() {
                        // 进入相册 以下是例子：用不到的api可以不写
                        PictureSelector.create(IdentificationActivity.this)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .theme(R.style.picture_default_style1)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                                .maxSelectNum(1)// 最大图片选择数量 int
                                .minSelectNum(1)// 最小选择数量 int
                                .imageSpanCount(4)  // 每行显示个数 int
                                .isCamera(true)// 是否显示拍照按钮 true or false
                                .compress(true)// 是否压缩 true or false
                                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .forResult(10005);//结果回调onActivityResult code     ;
                    }
                });
                break;
            case R.id.btn_identification:
                HashMap<String, String> hashMap = new HashMap<>();
                if (files == null) {
                    T.showShort("请上传头像");
                    return;
                }
                if (TextUtils.isEmpty(idName.getText().toString())) {
                    T.showShort("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(idSex.getText().toString())) {
                    T.showShort("请选择性别");
                    return;
                }
                if (TextUtils.isEmpty(idAge.getText().toString())) {
                    T.showShort("请输入年龄");
                    return;
                }
                if (Integer.valueOf(idAge.getText().toString()) > 100) {
                    T.showShort("年龄不能100岁");
                    return;
                }
                if (TextUtils.isEmpty(id_city.getText().toString())) {
                    T.showShort("请选择城市");
                    return;
                }
                if (TextUtils.isEmpty(idDetailAddress.getText().toString())) {
                    T.showShort("请输入详情地址");
                    return;
                }
                if (type.equals("2")) {
                    if (TextUtils.isEmpty(idOccupation.getText().toString())) {
                        T.showShort("请输入职业");
                        return;
                    }
                }

                if (TextUtils.isEmpty(idWeChat.getText().toString())) {
                    T.showShort("请输入微信号码");
                    return;
                }
                if (TextUtils.isEmpty(idPhone.getText().toString())) {
                    T.showShort("请输入手机号码");
                    return;
                }

                if (!DateTool.checkPhone(idPhone.getText().toString())) {
                    T.showShort("请输入正确的手机号码");
                    return;
                }

                try {
                    hashMap.put("name", idName.getText().toString());
                    if (identificationBo != null) {
                        hashMap.put("id", identificationBo.getId() + "");
                    }
                    hashMap.put("sex", sex);
                    hashMap.put("age", idAge.getText().toString());
                    hashMap.put("city", tx);
                    if (type.equals("2")) {
                        hashMap.put("manAuthentication", swDaren.isChecked() ? "1" : "0");
                    }
                    hashMap.put("wechat", idWeChat.getText().toString());
                    hashMap.put("detailAddress", idDetailAddress.getText().toString());
                    hashMap.put("phone", idPhone.getText().toString());
                    hashMap.put("occupation", idOccupation.getText().toString());
                    hashMap.put("cardPositive", cardPositive);
                    hashMap.put("cardNegative", cardNegative);

                    if (type.equals("2")) {
                        if (swDaren.isChecked()) {
                            if (TextUtils.isEmpty(skill.getText().toString())) {
                                T.showShort("请输入技能");
                                return;
                            }
                        }

                        if (TextUtils.isEmpty(cardPositive)) {
                            T.showShort("请上传身份证正反面");
                            return;
                        }
                        hashMap.put("skill", skill.getText().toString());
                        presenter.userThirdLogin(files, hashMap);


                    } else {
                        if (TextUtils.isEmpty(idPosition.getText().toString())) {
                            T.showShort("请输入单位地址");
                            return;
                        }
                        if (TextUtils.isEmpty(businessLicense)) {
                            T.showShort("请上传营业执照");
                            return;
                        }

                        hashMap.put("companyName", idCompanyName.getText().toString());
                        hashMap.put("position", idPosition.getText().toString());
                        hashMap.put("businessLicense", businessLicense);
                        presenter.add_boss_authentication(files, hashMap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.layout_identification_card:
                Intent intent = new Intent(this, IdentityAuthenticationActivity.class);
                intent.putExtra("idType", "");
                startActivityForResult(intent, 30002);
                break;
            case R.id.layout_business_licence:
                intent = new Intent(this, IdentityAuthenticationActivity.class);
                intent.putExtra("idType", "11");
                startActivityForResult(intent, 30006);
                break;
            case R.id.id_occupation:
                Intent intents = new Intent(this, PublishGenreActivity.class);
                intents.putExtra("is_select", true);
                startActivityForResult(intents, 30008);
                break;
        }
    }

    String cardNegative = "", cardPositive = "", businessLicense = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 30002:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("cardNegative"))) {
                    cardNegative = data.getStringExtra("cardNegative");
                    cardPositive = data.getStringExtra("cardPositive");
                    identificationContent.setText("已上传身份证(正面/反面)");
                }
                break;
            case 30006:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("businessLicense"))) {
                    businessLicense = data.getStringExtra("businessLicense");
                    idBusinessLicense.setText("已上传(营业执照)");
                }
                break;

            case 30008:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("three"))) {
                   String text=data.getStringExtra("three");
                    idOccupation.setText(TextUtils.isEmpty(text)?"":text);
                }
                break;
            case 10005:
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                for (int i = 0; i < selectList.size(); i++) {
                    if (!TextUtils.isEmpty(selectList.get(i).getCompressPath())) {
                        files = new ArrayList<>();
                        files.add(new File(selectList.get(i).getCompressPath()));
                        AM.image().bindToCircleObject(new File(selectList.get(i).getCompressPath()), identificationImg);
                    } else {
                        T.showShort("图片错误");
                    }
                }
                break;
        }
    }

    @Override
    public void showLoginSuccess() {
        T.showShort("认证成功");
        finish();
    }

    IdentificationBo identificationBo;

    @Override
    public void showData(IdentificationBo identificationBo) {
        this.identificationBo = identificationBo;
        if (identificationBo != null) {
            idName.setText(identificationBo.getUser().getName());
            idSex.setText(identificationBo.getUser().getSex() == 0 ? "男" : "女");
            idAge.setText(identificationBo.getUser().getAge() + "");
            idOccupation.setText(identificationBo.getOccupation());
            id_city.setText(identificationBo.getUser().getCity());
            idWeChat.setText(identificationBo.getUser().getWechat());
            idPhone.setText(identificationBo.getPhone());
            idDetailAddress.setText(identificationBo.getUser().getDetailAddress());
            idCompanyName.setText(identificationBo.getCompanyName());
            idPosition.setText(identificationBo.getPosition());
            if (type.equals("2")) {
                if (identificationBo.getManAuthentication().equals("0")) {
                    swDaren.setChecked(false);
                } else {
                    swDaren.setChecked(true);
                    skill.setText(identificationBo.getSkill());
                }
            }

            if (!TextUtils.isEmpty(identificationBo.getCardNegative())) {
                identificationContent.setText("已上传身份证(正面/反面)");
                cardNegative = identificationBo.getCardNegative();
                cardPositive = identificationBo.getCardPositive();
            }
            if (!TextUtils.isEmpty(identificationBo.getBusinessLicense())) {
                idBusinessLicense.setText("已上传(营业执照)");
                businessLicense = identificationBo.getBusinessLicense();
            }
            if (!TextUtils.isEmpty(identificationBo.getUser().getUserHead())) {
                files = new ArrayList<>();
            }
            AM.image().bindToCircleObject(identificationBo.getUser().getUserHead(), identificationImg);
        }

    }

    @Override
    public void showIdentificationData(IDCardBo idCardBo) {

    }

    @Override
    public void showError(String error) {
        T.showShort(error);
    }
}
